﻿using System;

using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HZ.MBSM.DBUtility;

public partial class Supervise_TraHospital : System.Web.UI.Page, HZ.MBSM.BLL.TraDes
{
    public string _strEndDate, _strStartDate, _AreaId = "", _strUserType = "", _strAccountId = "", Display = "block";
    string strSort = "";
    private string DGJE = "", DHJE = "", bidprice = "", bakeprice = "", Nolimtprice = "", GMPprice = "", KeyPrice = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (HZ.MBSM.BLL.Login.CheckAssert(this.UseAccountType))
        {
            HZ.MBSM.Model.Account _Account = (HZ.MBSM.Model.Account)Session["Account"];
            if (_Account != null)
            {
                _AreaId = SysFun.ToTrim(_Account.AreaId);
                _strUserType = SysFun.ToTrim(_Account.Type);
                _strAccountId = SysFun.ToTrim(_Account.AccountId);
                if (!Page.IsPostBack)
                {
                    if (Request.QueryString["deal"] != null && Request.QueryString["deal"] != "")
                    {
                        switch(Request.QueryString["deal"].ToString())
                        {
                            case "未确认送货":
                                dealDrop.SelectedIndex = 0;
                                break;
                            case "送货中":
                                dealDrop.SelectedIndex = 1;
                                break;
                            case "已入库":
                                dealDrop.SelectedIndex = 2;
                                break;
                            case "无法配送":
                                dealDrop.SelectedIndex = 3;
                                break;
                            case "到期未送":
                                dealDrop.SelectedIndex = 4;
                               break;

                        }
                        
                    }
                }
                //如果当前使用人是配送企业
                if (_strUserType == "2")
                {
                    _AreaId = "530000";
                }
                strSort = _Account.Sort.Trim();

            }
            if (_strUserType == "3")
            {
                //如果当前用户是医院，那么就把地区隐藏
                labArea.Visible = false;
                Label1.Visible = false;
                Display = "none";
            }
            else
            {
                ////如果是监督机构或中介就根据其所在的地区来选择
                ////如果是省一级的监督机构就可以看到整个云南省的信息,如果是某个市的监督机构就只能看到本市的信息
                //System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
                //string _strAreaNameForm, _strAreaIdForm;
                //_strAreaNameForm = SysFun.ToTrim(Request.Form["txtAreaName"]);
                //_strAreaIdForm = SysFun.ToTrim(Request.Form["txtAreaId"]);
                //if (_strAreaNameForm != "" && _strAreaIdForm != "")
                //{
                //    strHtml.Append("<input type='text' name='txtAreaName' value ='" + _strAreaNameForm + "' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                //    strHtml.Append("<input type='text' name='txtAreaId'  value ='" + _strAreaIdForm + "' style='display: none' />");
                //}
                //else
                //{
                //    strHtml.Append("<input type='text' name='txtAreaName' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                //    strHtml.Append("<input type='text' name='txtAreaId' style='display: none' />");
                //}
                //if (_AreaId != "")
                //{
                //    strHtml.Append("<a href='javascript:AreaSelect(" + _AreaId + ")'>选择地区</a>");
                //}
                //labArea.Text = strHtml.ToString();
                //labArea.Visible = true;
                //Label1.Visible = true;
                //Display = "block";
                //如果是监督机构或中介就根据其所在的地区来选择
                //如果是省一级的监督机构就可以看到整个云南省的信息,如果是某个市的监督机构就只能看到本市的信息
                System.Text.StringBuilder strHtml = new System.Text.StringBuilder();
                string _strAreaNameForm, _strAreaIdForm;
                _strAreaNameForm = SysFun.IsSQL(SysFun.ToTrim(Request.Form["txtAreaName"]));
                _strAreaIdForm = SysFun.IsSQL(SysFun.ToTrim(Request.Form["txtAreaId"]));
                if (_strAreaNameForm != "" && _strAreaIdForm != "")
                {

                    strHtml.Append("<input type='text' name='txtAreaName' value ='" + _strAreaNameForm + "' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                    strHtml.Append("<input type='text' name='txtAreaId'  value ='" + _strAreaIdForm + "' style='display: none' />");
                }
                else
                {
                    string strTempAreaId = SysFun.ToTrim(Request.QueryString["AreaId"]);
                    if (strTempAreaId != "")
                    {
                        Db Db1 = new Db();
                        System.Data.IDataReader dr;
                        string strSql = "select * from area where areaid = " + strTempAreaId;
                        dr = Db1.DataReader(strSql);
                        while (dr.Read())
                        {
                            strHtml.Append("<input type='text' name='txtAreaName' value ='" + dr["AreaName"].ToString() + "' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                            strHtml.Append("<input type='text' name='txtAreaId'  value ='" + dr["AreaId"].ToString() + "' style='display: none' />");

                        }
                        dr.Close();
                        dr.Dispose();
                        Db1.Close();
                    }
                    else
                    {
                        strHtml.Append("<input type='text' name='txtAreaName' id='Text1' language='javascript' onclick='return Text1_onclick()'  InvertedComma='所属地区' readonly />");
                        strHtml.Append("<input type='text' name='txtAreaId' style='display: none' />");
                    }
                }
                if (_AreaId != "")
                {
                    strHtml.Append("<a href='javascript:AreaSelect(" + _AreaId + ")'>选择地区</a>");
                }
                labArea.Text = strHtml.ToString();
                labArea.Visible = true;
                Label1.Visible = true;
            }
            if (!IsPostBack)
            {
                //第一次调用时 得到传过来的AreaId
                string strTempAreaid = SysFun.IsSQL(SysFun.ToTrim(Request.QueryString["AreaId"]));
                if (strTempAreaid != "")
                {
                    _AreaId = strTempAreaid;
                }

                //<!--初始化统计时间
                int Year, Month, Day, DMonth, Year1;
                Year = DateTime.Now.Year;
                Year1 = Year;
                DMonth = DateTime.Now.Month;
                Month = DMonth - 1;
                if (Month == 0)
                {
                    Year1 -= 1;
                    Month = 12;
                }

                Day = DateTime.Now.Day;
                txtStartDate.Text = Year1.ToString() + "-" + Month.ToString() + "-01";
                txtEndDate.Text = Year.ToString() + "-" + DMonth.ToString() + "-01";

                _strEndDate = SysFun.ToTrim(Request.QueryString["EndDate"]);
                _strStartDate = SysFun.ToTrim(Request.QueryString["StartDate"]);
                if (_strEndDate != "")
                {
                    txtEndDate.Text = _strEndDate;
                }
                if (_strStartDate != "")
                {
                    txtStartDate.Text = _strStartDate;
                }
                //初始化统计时间-->

                //<!--初始化医院类型
                lstDistinction.Items.Add("全部");
                lstDistinction.Items.Add("三甲");
                lstDistinction.Items.Add("三乙");
                lstDistinction.Items.Add("二甲");
                lstDistinction.Items.Add("二乙");
                lstDistinction.Items.Add("一甲");
                lstDistinction.Items.Add("一乙");
                string _strHosptialType = SysFun.ToTrim(Request.QueryString["Distinction"]);
                if (_strHosptialType != "")
                {
                    lstDistinction.SelectedValue = _strHosptialType;
                }

                //初始化医院类型-->

            }

            if (Request.Form["butSelectAll"] == "查看全部")
            {

                string strSql = @"select  AccountId_YY,HospitalName,UserCode_YY,convert(numeric(20,2),sum(GoodsNum*TradePrice)) as DGJE ,convert(numeric(20,2),sum(inflownum*TradePrice)) as DHJE
                                ,convert(numeric(20,2),sum(case when GoodsState=0 then inflownum*TradePrice else 0 end)) as YZB,convert(numeric(20,2),sum(case when GoodsState=1 then inflownum*TradePrice else 0 end)) as BACG,convert(numeric(20,2),SUM(case when GoodsState=2 then inflownum*TradePrice else 0 end)) AS BXJ                                 
                                from tra_GoodsId where  {0}  group by AccountId_YY,HospitalName,UserCode_YY  Order By DHJE DESC,AccountId_YY";
                string _strtempWhere = fctConditions();
                strSql = String.Format(strSql, _strtempWhere);
                Db db1 = new Db();
                System.Data.IDataReader dr;
                dr = db1.DataReader(strSql);
                GridView1.DataSource = dr;
                GridView1.DataBind();
                dr.Close();
                dr.Dispose();
                db1.Close();
            }
            else
            {
                showGridView();
            }
        }
    }


    /// <summary>
    /// 数据绑定
    /// </summary>
    public void showGridView()
    {

        string strConditions = fctConditions();
        Db db = new Db();
        DbPage dbPage = new DbPage(db);
        dbPage.Table = "tra_GoodsId";                                               //要查询的表明
        dbPage.SelectFieldGroup = "AccountId_YY,HospitalName,UserCode_YY,DealStatus";
        dbPage.Key = "AccountId_YY";                                               //表的主键    
        dbPage.Where = strConditions;                                           //查询条件    
        dbPage.SelectField = "AccountId_YY,HospitalName,UserCode_YY,convert(numeric(20,2),sum(GoodsNum*TradePrice)) as DGJE ,convert(numeric(20,2),sum(inflownum*TradePrice)) as DHJE ,convert(numeric(20,2),sum(case when GoodsState=0 then inflownum*TradePrice else 0 end)) as bidprice,convert(numeric(20,2),sum(case when GoodsState=1 then inflownum*TradePrice else 0 end)) as bakeprice,convert(numeric(20,2),SUM(case when GoodsState=2 then inflownum*TradePrice else 0 end)) AS Nolimtprice,convert(numeric(20,2),SUM(case when GoodsState=3 then inflownum*TradePrice else 0 end)) AS GMPprice,convert(numeric(20,2),SUM(case when GoodsState=4 then inflownum*TradePrice else 0 end)) AS KeyPrice,case DealStatus  when 0 then '未确认送货' when 1 then '送货中' when 2 then '已入库' when 4 then '无法配送' when 5 then '到到期未送' end as DealStatus";//要显示的字段
        dbPage.PageIndex = SysFun.ToInt(Request["CurrentlyPageIndex"]);          //要显示第几页   
        dbPage.PageSize = 30;                                                    //没有显示记录条数   
        dbPage.OrderBy = "DHJE,AccountId_YY";                  //排序字段
        dbPage.OrderByIsDesc = true;
        dbPage.DGJE = "convert(numeric(20,2),sum(GoodsNum*TradePrice)) as DGJE";
        dbPage.DHJE = "convert(numeric(20,2),sum(inflownum*TradePrice)) as DHJE";
        dbPage.bidprice = "convert(numeric(20,2),sum(case when GoodsState=0 then inflownum*TradePrice else 0 end)) as bidprice";
        dbPage.bakeprice = "convert(numeric(20,2),sum(case when GoodsState=1 then inflownum*TradePrice else 0 end)) as bakeprice";
        dbPage.Nolimtprice = "convert(numeric(20,2),sum(case when GoodsState=2 then inflownum*TradePrice else 0 end)) as Nolimtprice";
        dbPage.GMPprice = "convert(numeric(20,2),sum(case when GoodsState=3 then inflownum*TradePrice else 0 end)) as GMPprice";
        dbPage.Keyprice = "convert(numeric(20,2),sum(case when GoodsState=4 then inflownum*TradePrice else 0 end)) as Keyprice";
        System.Data.IDataReader dr = dbPage.ExecuteReaderGroup(60);
        DGJE = dbPage.DGJE; DHJE = dbPage.DHJE; bidprice = dbPage.bidprice; bakeprice = dbPage.bakeprice; Nolimtprice = dbPage.Nolimtprice; GMPprice = dbPage.GMPprice; KeyPrice = dbPage.Keyprice;
        GridView1.DataSource = dr;
        GridView1.DataBind();
        dr.Close();
        dr.Dispose();
        dbPage.Db.Close();
        db.Close();
        this.DbPageFlip1.DbPage = dbPage;//将数据传给控键



    }
    /// <summary>
    /// 生成查询条件
    /// </summary>
    /// <returns></returns>
    public string fctConditions()
    {
        string _strTemp = " DealStatus >=0 and DealStatus <> 3 and", CompanyName = "", _UserCode, _strAreaIdForm, _strDistinction;
        //时间范围
        _strEndDate = txtEndDate.Text.ToString();
        _strStartDate = txtStartDate.Text.ToString();
        if (_strEndDate != "" && _strStartDate != "")
        {
            _strTemp += " isnull(hospitalinflowdate,'3000-12-30') >='" + _strStartDate + "' and isnull(hospitalinflowdate,'1900-01-01') <='" + _strEndDate + "' and";
        }
        //医院级别
        _strDistinction = lstDistinction.Text;
        switch (_strDistinction)
        {
            case "全部":
                _strDistinction = "全部";
                break;
            case "三甲":
                _strDistinction = "0";
                break;
            case "三乙":
                _strDistinction = "1";
                break;
            case "二甲":
                _strDistinction = "2";
                break;
            case "二乙":
                _strDistinction = "3";
                break;
            case "一甲":
                _strDistinction = "4";
                break;
            case "一乙":
                _strDistinction = "5";
                break;
        }
        if (_strDistinction != "全部")
        {
            _strTemp += " Distinction =" + _strDistinction + " and";
        }

        //如果当前使用人是配送企业
        if (_strUserType == "2")
        {
            if (strSort == "0")
            {
                _strTemp += " AccountId_sc=" + _strAccountId + " and";
            }
            else
            {
                _strTemp += " AccountId_PS=" + _strAccountId + " and";
            }
        }

        //根据登录人和地区确定医院范围
        if (_strUserType == "3")
        {
            _strTemp += "  AccountId_YY=" + _strAccountId + " and";
        }
        else
        {
            //医院编码
            _UserCode = txtUserCode.Text.ToString();
            if (_UserCode != "")
            {
                _strTemp += " UserCode_YY like '%" + _UserCode + "%' and";
            }

            //医院名称
            CompanyName = txtAttorneyName.Text.ToString();
            if (CompanyName != "")
            {
                _strTemp += " hospitalName like '%" + CompanyName + "%' and";
            }
            _strAreaIdForm = SysFun.ToTrim(Request.Form["txtAreaId"]);
            //if (_strAreaIdForm != "" && _strAreaIdForm != "530000")
            //{
            //    _AreaId = _strAreaIdForm;
            //    _strTemp += "  AccountId_YY in (select Accountid from hospital where areaid=" + _strAreaIdForm + ") and";               
            //}
            //else if (_AreaId != "" && _AreaId != "530000")
            //{
            //    _strTemp += "  AccountId_YY in (select Accountid from hospital where areaid=" + _AreaId + ") and";
            //}
            if (_strAreaIdForm != "" && _strAreaIdForm != "530000")
            {
                _AreaId = _strAreaIdForm;
            }
            _strTemp += SysFun.AreaIdWhere(_AreaId);
        }
        if (dealDrop.SelectedValue != "")
        { 
            if (dealDrop.SelectedValue == "0")
            {
                _strTemp += " DealStatus=" + dealDrop.SelectedValue + " and buystatus=2 and";
            }
            else
            {
                _strTemp += " DealStatus=" + dealDrop.SelectedValue + " and";
            }
        }
        if (_strTemp != "")
        {
            _strTemp = "  " + _strTemp.Substring(0, _strTemp.Length - 3);
        }
        return _strTemp;
    }
    protected void ToEcxul_Click(object sender, EventArgs e)//导出
    {

        //0 原中标商品 1 自行采购  2  22种降价 3 血液制品 4 重点监控 默认为‘0’
        Db db = new Db();
        System.Data.IDataReader dr;
        string _strSql = "Select HospitalName as 医院名称,UserCode_YY as 注册号,convert(numeric(20,2),sum(GoodsNum*TradePrice)) as '订货金额（元）' ,convert(numeric(20,2),sum(inflownum*TradePrice)) as  '到货金额（元）' ,convert(numeric(20,2),sum(case when GoodsState=0 then inflownum*TradePrice else 0 end)) as '原中标（元）',convert(numeric(20,2),sum(case when GoodsState=1 then inflownum*TradePrice else 0 end)) as '自行采购（元）',convert(numeric(20,2),SUM(case when GoodsState=2 then inflownum*TradePrice else 0 end)) AS '22种降价（元）',convert(numeric(20,2),SUM(case when GoodsState=3 then inflownum*TradePrice else 0 end)) AS 血液制品,convert(numeric(20,2),SUM(case when GoodsState=4 then inflownum*TradePrice else 0 end)) AS 重点监控,case DealStatus  when 0 then '未确认送货' when 1 then '送货中' when 2 then '已入库' when 4 then '无法配送' when 5 then '到到期未送' end as 采购状态 From tra_GoodsId Where     " + fctConditions() + "    Group By AccountId_YY,HospitalName,UserCode_YY,DealStatus Order By '订货金额（元）' Desc";

        dr = db.DataReader(_strSql);
        this.GridView2.DataSource = dr;
        this.GridView2.DataBind();
        db.Close();
        dr.Close();
        dr.Dispose();
        SysFun.WriteToExcel(GridView2, this.Page, "按医院查询.xls");



    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //OverRide　为了使导出成Excel可行！
    }
    #region TraDes 成员

    public string Name
    {
        get { return "按医院查询"; }
    }

    public string Describe
    {
        get { return ""; }
    }

    public string ParentName
    {
        get { return "交易查询"; }
    }

    public System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> UseAccountType
    {
        get
        {
            System.Collections.Generic.List<HZ.MBSM.DAL.AccountType> _AccountType = new System.Collections.Generic.List<HZ.MBSM.DAL.AccountType>();
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumAttorney);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumSupervise);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumCompany);
            _AccountType.Add(HZ.MBSM.DAL.AccountType.enumSuperviseChildCheck);
            return _AccountType;
        }
    }
    #endregion

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            e.Row.Cells[0].Text = "合计";
            e.Row.Cells[1].Text = "";
            e.Row.Cells[2].Text = DGJE;
            e.Row.Cells[3].Text = DHJE;
            e.Row.Cells[4].Text = bidprice;
            e.Row.Cells[5].Text = bakeprice;
            e.Row.Cells[6].Text = Nolimtprice;
            e.Row.Cells[7].Text = GMPprice;
            e.Row.Cells[8].Text = KeyPrice;

        }
    }
}
